package com.greenhouse9.prog01.split;

import org.apache.commons.cli.CommandLine;

import com.greenhouse9.prog01.Prog1;

public class Command {

	CommandLine cl;

	String optByteSize;
	String [] leftargs;
	String inputfile;
	String outputfile;

	public void setCommandLine(CommandLine commandLine){
		cl = commandLine;
	}

	public int validate(){
		if (cl.hasOption("b")){
			optByteSize = cl.getOptionValue("b");
		}
		else {
			return -1;
		}

		leftargs = cl.getArgs();

		if(leftargs.length<1 || leftargs.length > 2){
			return -1;
		}

		inputfile = leftargs[0];

		if(leftargs.length == 2){
			outputfile = leftargs[1];
		}
		else {
			outputfile = "x";
		}

		return 0;
	}

	public void execute (){
		System.out.println("optByteSize: " + optByteSize);

		Prog1 prog = new Prog1(inputfile); //args[0] is file or directory name

	    prog.checkFileExists();
	    prog.outputData();

	    int size = Integer.parseInt(optByteSize);
	    prog.outputData(size);
	    System.out.println();
	    System.out.println();

	    long filesize = prog.getFileSize();
	    int offset = 0;
	    Prog3 prog3 = new Prog3(outputfile);

	    while (filesize > offset){
		    System.out.print(prog3.nextFilename() + ": ");
		    prog.outputData(prog3.nextFilename(), offset, size);
		    System.out.println();
		    offset = offset + size;
	    }

	}

	public void printError(){
		System.err.println("Error!");
	}
}
